package school.valon.persistence.dao.base.impl;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import javax.persistence.EntityManager;

import school.valon.persistence.dao.base.GenericDao;

public abstract class GenericDaoImpl<T, Key> implements GenericDao<T, Key> {

    protected EntityManager em;
    
    public void setEntityManager(EntityManager em) {
    	this.em = em;
    }

    private Class<T> type;

    @SuppressWarnings("unchecked")
	public GenericDaoImpl() {
        Type t = getClass().getGenericSuperclass();
        ParameterizedType pt = (ParameterizedType) t;
        type = (Class<T>) pt.getActualTypeArguments()[0];
    }

    @Override
    public T create(final T t) {
        this.em.persist(t);
        return t;
    }

    @Override
    public void delete(final Key id) {
    	/*T entity = this.em.find(type, id);
        if (entity != null) {
        	this.em.remove(entity);
        }*/
    	em.createNamedQuery(type.getSimpleName() + ".deleteById")
    		.setParameter("P1", id).executeUpdate();
    }

    @Override
    public T find(final Key id) {
        return (T) this.em.find(type, id);
    }

    @Override
    public T update(final T t) {
        return this.em.merge(t);    
    }

    @Override
    public void detach(final Object t) {
        this.em.detach(t);    
    }
}